using Microsoft.Extensions.DependencyInjection;
using Vin.Extension.Win32.Command.Node;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.JsonCategory;

namespace Vin.Extension.Win32.Command.Workflow;

public class WorkflowManager
{
    public static async Task StartWorkflow(string filePath)
    {
        await VinApp.CreateScopeAsync(async (provider) =>
        {
            var workflowContext = provider.GetRequiredService<IWorkflowContext>();
            var workflowData = await LoadWorkflowData(filePath);
            workflowContext.WorkflowData = workflowData;

            try
            {
                await ExecuteNodeGroup(workflowData.StartNodeGroup);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Workflow end.");
        });
    }

    public static async Task ExecuteNodeGroup(NodeGroup nodeGroup)
    {
        await Task.Run(async () =>
        {
            var workflowContext = VinApp.GetRequiredServiceByHttpContext<IWorkflowContext>();
            var nodeData = workflowContext.WorkflowData.NodeDataList.FirstOrDefault(x => x.Id == nodeGroup.Id)!;
            var context = workflowContext.NodeContext(nodeGroup.Id) ??
                          new NodeContext(nodeGroup, new NodeExecuteData(nodeData));
            context.Port = nodeGroup.Port;
            await nodeData.Node.InvokeAsync(context, workflowContext);
        });
    }

    /// <summary>
    /// 根据文件路径加载工作流
    /// </summary>
    public static async Task<WorkflowData> LoadWorkflowData(string filePath)
    {
        return (await File.ReadAllTextAsync(filePath)).ToUnderLineObject<WorkflowData>() ??
               throw new Exception("Workflow file is invalid.");
    }
}